<template>
  <div class="search-zone">
    <!--按条件查询-->
    <form>
      姓名：
      <el-input placeholder="请输入姓名" style="width: 100px" v-model="stuName"></el-input>
      性别：
      <el-select v-model="sex" placeholder="请选择性别">
        <el-option label="不限" value="0"></el-option>
        <el-option label="男生" value="1"></el-option>
        <el-option label="女生" value="2"></el-option>
      </el-select>
      按时间筛选：
      <el-date-picker v-model="startDate" placeholder="请选择开始日期" type="date"
                      value-format="YYYY-MM-DD"></el-date-picker>
      <el-date-picker v-model="endDate" placeholder="请选择结束日期" type="date"
                      value-format="YYYY-MM-DD"></el-date-picker>
      <el-button-group>
        <el-button type="primary" @click="addStudent()">
          <el-icon>
            <Plus/>
          </el-icon>
          添加
        </el-button>
        <el-button type="success" @click="getStuList()">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>

        <el-button type="warning" @click="removeCondition()">
          <el-icon>
            <RefreshLeft/>
          </el-icon>
          清除筛选条件
        </el-button>
      </el-button-group>
    </form>
  </div>
  <div>
    <!--服务端渲染表格-->
    <el-table :data="studentList" stripe table-layout='auto'>
      <el-table-column prop="id" label="学生ID"></el-table-column>
      <el-table-column prop="name" label="学生姓名"></el-table-column>
      <el-table-column prop="age" label="学生年龄"></el-table-column>
      <el-table-column prop="sex" label="学生性别">
        <template #default="scope">
          <!--三元表达式-->
          {{ scope.row.sex == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="phoneNumber" label="电话号码"></el-table-column>
      <el-table-column prop="birthday" label="生日"></el-table-column>
      <el-table-column prop="profile" label="头像">
        <template #default="scope">
          <el-image :src="serverPath+scope.row.profile" style="width: 60px;height: 60px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!--#default插槽：scope是变量名称 可以随便取 作用：得到表单某一行的整个对象（包括数据对象 以及页面的标签对象等等）
         scope.row 得到当前行的对象 scope.row.id得到当前行的id-->
        <template #default="scope">
          <el-button-group>
            <el-button type="danger" @click="deleteStudent(scope.row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-button>
            <el-button type="primary" @click="modifyStudent(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="demo-pagination-block">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" :page-sizes="[3, 4, 5, 10]"
                   layout="total, sizes, prev, pager, next ,jumper" :total="total">
    </el-pagination>
  </div>

  <div>
    <!--el-dialog对话框 title：标题 width：宽度-->
    <el-dialog v-model="dialogVisible" title="修改学生信息" width="30%">
      <!--表单元素的基本使用 el-form 等同于 form表单  el-form-item是表单中的美一行 由框架底层提供样式布局-->
      <!--userForm双向绑定 所以userForm.userName是双重双向绑定-->
      <el-form :model="stuForm" ref="stuForm" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="stuForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="stuForm.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="stuForm.sex" placeholder="请选择性别">
            <el-option label="男生" value="1"></el-option>
            <el-option label="女生" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="stuForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker type="date" value-format="YYYY-MM-DD" v-model="stuForm.birthday" placeholder="请选择生日"
                          style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="profile" label="头像" v-model="stuForm.profile">
          <el-image :src="serverPath+stuForm.profile" style="width: 60px;height: 60px"></el-image>
        </el-form-item>
      </el-form>
      <el-upload class="upload"
                 ref="upload"
                 action="string"
                 :file-list="fileList"
                 :auto-upload="false"
                 :http-request="uploadFile"
                 :on-change="handleChange"
                 :on-preview="handlePreview"
                 :on-remove="handleRemove"
                 multiple="multiple">
        <el-button slot="trigger"
                   size="small"
                   type="primary"
                   @click="delFile">更换头像
        </el-button>
      </el-upload>
      <el-button type="primary"
                 @click="onSubmit">保存
      </el-button>

      <!--#footer代表当前template中的内容为当前对话框的页脚-->
      <template #footer>
        <!--<span class="dialog-footer"></span>表示使用element-ui中提供的样式 可以不写-->
        <span class="dialog-footer">
          <el-button type="primary" @click="modifyStudentAck()">确定</el-button>
          <el-button type="primary" @click="dialogVisible=false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-dialog v-model="delDialogVisible" title="确定要删除吗" width="30%">
      <!--#footer代表当前template中的内容为当前对话框的页脚-->
      姓名：{{ deleteStuInfo.name }}
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="deleteStudentAck()">确定</el-button>
          <el-button type="primary" @click="delDialogVisible=false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <div>
    <el-dialog v-model="addDialogVisible" title="添加一位学生" width="30%">
      <el-form :model="addStuForm" ref="addStuForm" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addStuForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addStuForm.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="addStuForm.sex" placeholder="请选择性别">
            <el-option label="男生" value="1"></el-option>
            <el-option label="女生" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="addStuForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker type="date" value-format="YYYY-MM-DD" v-model="addStuForm.birthday" placeholder="请选择生日"
                          style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-upload class="upload"
                 ref="upload"
                 action="string"
                 :file-list="fileList"
                 :auto-upload="false"
                 :http-request="uploadFile"
                 :on-change="handleChange"
                 :on-preview="handlePreview"
                 :on-remove="handleRemove"
                 multiple="multiple">
        <el-button slot="trigger"
                   size="small"
                   type="primary"
                   @click="delFile">添加/更换头像
        </el-button>
      </el-upload>
      <el-button type="primary"
                 @click="onSubmit">确认添加/修改
      </el-button>

      <!--#footer代表当前template中的内容为当前对话框的页脚-->
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="addStudentAck()">确定</el-button>
          <el-button type="primary" @click="addDialogVisible=false;this.$refs.addStuForm.resetFields()">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

</template>


<script>


import axios from "axios";
import {ElNotification} from 'element-plus'
import {Search} from '@element-plus/icons-vue'

export default {

  created() {
    this.getStuList();
  },

  name: "UserList.vue",
  data() {
    return {
      stuName: '',
      sex: '',
      startDate: '',
      endDate: '',
      dialogVisible: false,
      delDialogVisible: false,
      addDialogVisible: false,
      rules: {
        //required:true 必填 提示信息 message:'请输入用户名' 触发规则：trigger:'blur' blur指失去焦点
        name: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          //长度为2-10个字符
          {min: 2, max: 10, message: '姓名长度为2-10个字符', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          //大于0的正整数
          {pattern: /^\+?[1-9]\d*$/, message: '年龄为正整数', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {pattern: /^1[3578]\d{9}$/, message: '电话号码有误请检查！', trigger: 'blur'}
        ]
      },
      deleteStuInfo: {
        id: '',
        name: ''
      },
      addStuForm: {
        id: '',
        name: '',
        age: '',
        sex: '',
        phoneNumber: '',
        birthday: '',
        profile: ''
      },
      stuForm: {
        id: '',
        name: '',
        age: '',
        sex: '',
        phoneNumber: '',
        birthday: '',
        profile: ''
      },
      studentList: [],
      // 总条数
      total: 0,
      //参数
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 显示一页多少条数据
        pagesize: 3
      },
      // el-upload组件绑定的属性—— :file-list=“fileList”,渲染后fileList[index]是Object类型,而不是后台所需的File类型,
      // 而这个组件已经把对应的File类型存储到了fileList[index].raw这个属性里,直接拿来用就好.
      fileList: [],
      // 不支持多选
      multiple: false,
      formData: "",
      profile: '',
      serverPath: 'http://localhost:8080/img/'
    }
  },

  methods: {

    //添加学生
    addStudent() {
      this.addDialogVisible = true;
    },
    addStudentAck() {
      let param = {
        name: this.addStuForm.name,
        age: this.addStuForm.age,
        sex: this.addStuForm.sex,
        phoneNumber: this.addStuForm.phoneNumber,
        birthday: this.addStuForm.birthday,
        profile: this.profile //这里要注意
      }
      console.log("add" + this.stuForm.profile)
      axios.post('/api/student/addStudent', param).then(response => {
        ElNotification({
          title: '添加成功！',
          message: '添加用户成功',
          type: 'success',
        })
        //刷新表格 关闭对话框
        this.getStuList();
        this.dialogVisible = false;
      })
    },

    //删除学生
    deleteStudent(scope_row) {
      this.delDialogVisible = true;
      this.deleteStuInfo.id = scope_row.id;
      this.deleteStuInfo.name = scope_row.name;
    },
    deleteStudentAck() {
      let param = new URLSearchParams()
      param.append('id', this.deleteStuInfo.id);

      axios.post('/api/student/deleteStudent', param).then(response => {
        ElNotification({
          title: '删除成功！',
          message: '您已成功删除该信息',
          type: 'success',
        })
        //刷新表格 关闭对话框
        this.getStuList();
        this.delDialogVisible = false;
      })
    },
    //修改学生
    modifyStudent(scope_row) {
      this.dialogVisible = true;
      console.log(scope_row.profile)
      this.stuForm.id = scope_row.id
      this.stuForm.name = scope_row.name
      this.stuForm.age = scope_row.age
      this.stuForm.sex = scope_row.sex == '1' ? '男生' : '女生'
      this.stuForm.phoneNumber = scope_row.phoneNumber
      this.stuForm.birthday = scope_row.birthday
      this.stuForm.profile = scope_row.profile
    },
    modifyStudentAck() {
      let param = {
        id: this.stuForm.id,
        name: this.stuForm.name,
        age: this.stuForm.age,
        sex: this.stuForm.sex == '男生' ? 1 : 2,
        phoneNumber: this.stuForm.phoneNumber,
        birthday: this.stuForm.birthday,
        profile: this.profile //这里要注意
      }
      console.log("hou" + this.stuForm.profile)
      axios.post('/api/student/updateStudent', param).then(response => {
        ElNotification({
          title: '修改成功！',
          message: '修改用户信息成功',
          type: 'success',
        })
        //刷新表格 关闭对话框
        this.getStuList();
        this.dialogVisible = false;
      })
    },
    getStuList() {
      let param = new URLSearchParams()
      param.append('nowPage', this.queryInfo.pagenum);
      param.append('pageSize', this.queryInfo.pagesize);

      //按性别筛选
      if (this.sex == '1' || this.sex == '2') {
        param.append('sex', this.sex);
      } else {
        param.append('sex', 0);
      }
      param.append('name', this.stuName);
      param.append('startDate', this.startDate);
      param.append('endDate', this.endDate);

      axios.post('/api/student/list', param).then(response => {
        //console.log(response.data.records)
        //把查出来的总条数赋值给属性
        this.total = response.data.total;
        //数据赋值
        this.studentList = response.data.records;
      })
    },
    removeCondition() {
      this.stuName = ''
      this.sex = ''
      this.startDate = ''
      this.endDate = ''
      this.getStuList();
    },
    //监听 pageSize 改变的事件
    handleSizeChange(newsize) {
      console.log(newsize)
      //最新的条数（newSize）赋值给 动态的 pagesie
      this.queryInfo.pagesize = newsize
      //获取到最新一页显示的数据  重新发送axios请求 这里是封装好的请求方法
      this.getStuList()
    },


    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      //把最新的页码（newPage）赋值给 动态的 pagenum
      this.queryInfo.pagenum = newPage
      //获取到最新显示的页码值  重新发送axios请求 这里是封装好的请求方法
      this.getStuList()
    },
    //点击上传文件触发的额外事件,清空fileList
    delFile() {
      this.fileList = [];
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      // console.log(this.fileList, "sb");
    },
    //自定义上传文件
    uploadFile(file) {
      this.formData.append("file", file.file);
      // console.log(file.file, "sb2");
    },
    //删除文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件
    handlePreview(file) {
      console.log(file);
    },
    //保存按钮
    onSubmit() {
      let formData = new FormData();
      formData.append("stuImg", this.fileList[0].raw);//拿到存在fileList的文件存放到formData中
      axios.post('/api/file/uploadImgByAbsolute', formData, {
        "Content-Type": "multipart/form-data;charset=utf-8"
      }).then(res => {
        //给文件属性赋值 这里已经成功获取到了图片的名称
        this.profile = res.data;
        //弹出提示
        ElNotification({
          title: '上传头像成功！',
          message: '上传头像成功',
          type: 'success',
        })

      })
    },
  }
}


</script>


<style>
/*分页插件样式*/
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.search-zone {
  margin-top: 20px;
  margin-bottom: 10px;
}
</style>
